package com.bi.socket.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * webSocket服务类
 */
@Component
@ServerEndpoint(value = "/websocket/{userId}")        //测试
@Slf4j
public class WebSocketServer {
    //模拟多线程，线程安全的
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    //每个客户端对应的webSocket对象
    private static ConcurrentHashMap<Long , WebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    //会话session
    private Session session;

    //接收的userID
    private Long userId;
    /**
     *连接成功调用的方法
     */
    @OnOpen
    public void open(Session session, @PathParam("userId") String userId){
        this.session = session;
        this.userId = Long.valueOf(userId);
        if (webSocketMap.containsKey(this.userId)){
            //新消息
            webSocketMap.remove(this.userId);
            webSocketMap.put(this.userId,this);
        }else {
            webSocketMap.put(this.userId,this);
            //这里的人数要发生变化
            addOnlineCount();
        }
        log.info("用户连接:{},当前人数:{}",this.userId,onlineCount);
    }

    /**
     *连接关闭调用的方法
     */
    @OnClose
    public void close(){
        //1:这里首先判断用户是连接
        if (webSocketMap.containsKey(userId)){
            //2：如果存在则将此用户移除
            webSocketMap.remove(userId);
            //3:人数减一
            subOnlineCount();
        }
        log.info("用户退出:{},当前人数:{}",userId,onlineCount);
    }

    /**
     * 收到客户端发送过来的信息调用的方法
     */
    @OnMessage
    public void message(String message) throws IOException {
        log.info("用户:{},消息：{}",userId,message);
        //这里该怎么处理呢？
        //todo 这里要校验当前用户是否在线（连接）
        //暂时就直接发送消息吧
        WebSocketServer webSocketServer = webSocketMap.get(userId);
        webSocketServer.sendMessage(message);
    }


    public static synchronized AtomicInteger getOnlineCount(){
        return onlineCount;
    }
    public static synchronized void addOnlineCount(){
        WebSocketServer.onlineCount.getAndIncrement();
    }

    public static synchronized void subOnlineCount(){
        WebSocketServer.onlineCount.getAndDecrement();
    }

    /**
     * 这里就是服务器主动发送的消息
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * todo 自定义发送消息
     */
    public  void sendInfo(String message,Long userId) throws IOException {
        WebSocketServer webSocketServer = webSocketMap.get(userId);
        if (webSocketServer!=null){
            webSocketServer.sendMessage(message);
        }else {
            log.info("用户不存在{}",userId);
        }
    }
}
